<template>
  <div class="app-container home">
    <div class="concent">
      <!-- <div class="toprow">
        <h2>样本统计</h2>
        <div>
          <el-tooltip class="item"
                      effect="dark"
                      content="显隐列"
                      placement="top"
                      v-if="checkAlldata">
            <el-button size="mini"
                       circle
                       icon="el-icon-menu"
                       @click="showColumn" />
          </el-tooltip>
          <el-button type="text"
                     style="color: #aa2299">刷新</el-button>
        </div>

      </div> -->
      <div class="rowbtn">
        <div class="left">
          <!-- 分享按钮 -->
          <div class="sambtn"
               @click="share">
            <img src="@/assets/images/sample/Slice 20@2x.png"
                 alt="" />
            分享
          </div>
          <el-button-group>
            <el-button :class="type == 1 ? 'active button' : 'button'"
                       @click="typeClick(1, 'PGTA')">PGT-A</el-button>
            <el-button :class="type == 2 ? 'active button' : 'button'"
                       @click="typeClick(2, 'PGTM')">PGT-M</el-button>
            <el-button :class="type == 3 ? 'active button' : 'button'"
                       @click="typeClick(3, 'PGTSR')">PGT-SR</el-button>
            <el-button :class="type == 4 ? 'active button' : 'button'"
                       @click="typeClick(4, 'NICS')">NICS</el-button>
          </el-button-group>
        </div>
        <div class="right">
          <el-input style="width: 250px"
                    v-model="queryParams.searchValue"
                    placeholder="送检单位/姓名/送检医生"
                    clearable />
          <el-button type="primary"
                     icon="el-icon-search"
                     size="mini"
                     @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
                     size="mini"
                     @click="resetQuery">重置</el-button>
        </div>
      </div>
      <div class="body">
        <el-col :span="24"
                :xs="24">
          <el-row :gutter="10"
                  class="mb8">
            <el-col :span="4">
              <el-button style="background-color: #aa2299; color: white;"
                         plain
                         icon="el-icon-download"
                         size="mini"
                         @click="handleExport"
                         v-hasPermi="['check:sample:export']">导出</el-button>
            </el-col>
            <el-col :span="20">
              <div class="toprow">
                <el-tooltip class="item"
                            effect="dark"
                            content="显隐列"
                            placement="top"
                            v-if="checkAlldata">
                  <el-button size="mini"
                             circle
                             icon="el-icon-menu"
                             @click="showColumn" />
                </el-tooltip>
              </div>
            </el-col>
          </el-row>

          <el-table :data="dataList"
                    height="calc(100vh - 320px)"
                    @selection-change="handleSelectionChange"
                    border>
            <el-table-column type="selection"
                             sortable
                             :selectable="handleSelectable">
            </el-table-column>
            <el-table-column label="序号"
                             align="center"
                             type="index"
                             width="80px"
                             sortable></el-table-column>
            <el-table-column v-for="(item, ind) in headlist"
                             :key="ind"
                             :label="item.fieldNameCn"
                             :prop="item.fieldName"
                             show-overflow-tooltip
                             width="200px"
                             align="center">
              <template slot-scope="scope">
                <div v-if="item.fieldName == 'patient_name'"
                     :style="getCellColor(scope.row)">
                  {{ scope.row[item.fieldName] }}
                </div>

                <div v-if="item.fieldName != 'patient_name'">
                  {{ scope.row[item.fieldName] }}
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作"
                             align="center"
                             class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-edit"
                           @click="handleUpdate(scope.row)"
                           v-hasPermi="['check:sample:edit']">修改</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0"
                      :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination="getList" />
        </el-col>
      </div>
    </div>
    <el-dialog title="分享"
               :visible.sync="isShareOpen">
      <el-form :model="shareForm"
               ref="shareForm"
               :rules="rules">
        <el-form-item label="所属医院"
                      :label-width="formLabelWidth">
          <el-input style="width: 220px"
                    :value="dept.deptName"
                    readonly></el-input>
        </el-form-item>
        <el-form-item label="选择医生"
                      :label-width="formLabelWidth"
                      prop="sharedIds">
          <el-select v-model="shareForm.sharedIds"
                     multiple
                     filterable
                     placeholder="请选择医生">
            <el-option v-for="user in userOptions"
                       :key="user.userId"
                       :label="user.nickName"
                       :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   class="button"
                   @click="shareConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title"
               :visible.sync="open"
               append-to-body>
      <el-transfer :titles="['显示', '隐藏']"
                   v-model="checkdata"
                   :data="checkAlldata"
                   sortable
                   @change="dataChange">
        <div slot="left">
          <ul>
            <!-- 自定义左侧内容 -->
            <li v-for="item in leftdata"
                :key="item.id">{{item.id}}</li>
          </ul>
        </div>
      </el-transfer>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitOk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改   -->
    <el-dialog title="修改信息"
               :visible.sync="isSampleOpen">
      <el-form :model="sampleForm"
               ref="sampleForm"
               :rules="sampleRules">
        <el-form-item label="所属医院"
                      :label-width="formLabelWidth">
          <el-input style="width: 220px"
                    :value="sampleForm.sjdwName"
                    readonly></el-input>
        </el-form-item>
        <el-form-item label="选择医生"
                      :label-width="formLabelWidth"
                      prop="sharedIds">
          <el-select v-model="sampleForm.sjys"
                     placeholder="请选择医生">
            <el-option v-for="user in userOptions"
                       :key="user.userId"
                       :label="user.nickName"
                       :value="user.nickName"></el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="受检人手机号" prop="patientPhone" :label-width="formLabelWidth">-->
        <!--          <el-input style="width: 220px"-->
        <!--                    v-model="sampleForm.patientPhone"-->
        <!--                    placeholder="请输入手机号" maxlength="20"/>-->

        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   class="button"
                   @click="sampleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSampleListBySampleDecWay, shareSamples } from "@/api/check/sample";
import { getAllList, getPagefielduserSava } from "@/api/check/pagefielduser";
import Sortable from "sortablejs";
import {
  getUserListByDeptId,
  getUserListByDeptName,
} from "@/api/system/custom";
import { updateSample } from "@/api/check/item";

export default {
  name: "Index",
  data () {
    return {
      isSampleOpen: false,
      formLabelWidth: "100px",

      // 版本号
      version: "3.8.5",
      type: 1,
      isShareOpen: false,
      formLabelWidth: "100px",
      //数据列表
      dataList: [],
      // 总条数
      total: 0,
      // 用户表格数据
      itemList: [],
      // 查询参数
      queryParams: {
        searchValue: undefined,
        pageNum: 1,
        pageSize: 10,
        sampleDecWay: "PGTA",
      },
      status: false,

      dept: {},
      user: {},
      userOptions: [],

      sampleForm: {
        sjdwName: undefined,
        patientPhone: undefined,
        nickName: undefined,
        id: undefined,
      },

      shareForm: {
        sharedId: undefined,
        deptId: undefined,
        ids: undefined,
      },

      // 表单校验
      rules: {
        userId: [{ required: true, message: "医生不能为空", trigger: "blur" }],
      },

      sampleRules: {
        patientPhone: [
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
      },

      open: false,
      title: "隐藏列",
      headlist: [],
      leftdata: [],
      checkdata: [],
      checkAlldata: [],
      activeName: "PGTA",
    };
  },

  created () {
    this.getAllListData();
    this.getDept();
  },

  mounted () {
    const params = {
      userId: this.$store.state.user.userId,
      type: this.type,
    };
  },

  methods: {
    getUserList () {
      var that = this;
      var form = {};
      form.deptName = that.sampleForm.sjdwName;
      getUserListByDeptName(form).then((response) => {
        if (response.code == "200" && response.data) {
          that.userOptions = response.data;
        }
      });
    },
    sampleConfirm: function () {
      var that = this;
      that.$refs["sampleForm"].validate((valid) => {
        if (valid) {
          var form = that.sampleForm;
          updateSample(form).then((response) => {
            //需要判断当前传入的userId是否有deptId，没有的话提示
            this.$modal.msgSuccess("修改成功");
            this.isSampleOpen = false;
            that.getList();
          });
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.sampleReset();
      const id = row.id || this.ids;
      this.isSampleOpen = true;
      this.sampleForm.sjdwName = row.sjdw_name;
      this.title = "修改样本信息";
      this.sampleForm.id = id;
      this.getUserList();
    },
    sampleReset () {
      this.sampleForm = {
        sjdwName: undefined,
        patientPhone: undefined,
        nickName: undefined,
        id: undefined,
      };
    },

    shareReset () {
      this.shareForm = {
        sharedId: undefined,
        deptId: undefined,
        ids: undefined,
      };
    },

    getCellColor (row) {
      var nickName = this.$store.state.user.nickName;
      if (row.sjys != nickName && row.is_share && row.is_share == 1) {
        return {
          background: "#aa2299",
          color: "#ffffff",
        };
      }
    },

    shareConfirm: function () {
      var that = this;
      this.$refs["shareForm"].validate((valid) => {
        if (valid) {
          var sharedIds = that.shareForm.sharedIds;
          var shareForm = {};
          if (sharedIds != null && sharedIds.length > 0) {
            var sharedId = "";
            for (var i = 0; i < sharedIds.length; i++) {
              if (i == 0) {
                sharedId = sharedIds[i];
              } else {
                sharedId += "," + sharedIds[i];
              }
            }
            shareForm.sharedId = sharedId;
          }
          shareForm.deptId = this.dept.deptId;
          shareForm.ids = this.ids;
          shareSamples(shareForm).then((response) => {
            //需要判断当前传入的userId是否有deptId，没有的话提示
            this.$modal.msgSuccess("分享成功");
            this.isShareOpen = false;
          });
        }
      });
    },

    getPagefielduserSavaData () {
      const arr = [];
      let brr = []
      this.leftdata.forEach(item => {
        brr.push(item.fieldId)
        arr.push({
          id: item.id || null,
          page: item.page,
          type: item.type,
          fieldId: item.fieldId,
          isShow: item.isShow,
        });
      })
      this.checkAlldata.forEach((item) => {
        if (!brr.includes(item.fieldId)) {
          arr.push({
            id: item.id || null,
            page: item.page,
            type: item.type,
            fieldId: item.fieldId,
            isShow: item.isShow,
          });
        }
      });
      getPagefielduserSava(arr).then((res) => {
        this.open = false;
        this.getAllListData(true);
      });
    },
    submitOk () {
      this.getPagefielduserSavaData();
    },
    // 右侧列表元素变化
    dataChange (data) {
      this.checkAlldata.forEach((item) => {
        if (data.includes(item.key)) {
          item.isShow = "0";
        } else {
          item.isShow = "1";
        }
      });
    },
    // 打开显隐列dialog
    showColumn () {
      this.open = true;
      if (this.open) {
        this.$nextTick(() => {
          var arr = document.getElementsByClassName("el-transfer-panel__list")[0]
          Sortable.create(arr, {
            onEnd: this.onDragEnd
          });
        })
      }
      this.getAllListData(true);
    },
    onDragEnd (event) {
      const movedItem = this.leftdata.splice(event.oldIndex, 1)[0];
      this.leftdata.splice(event.newIndex, 0, movedItem);
    },
    getAllListData (state) {
      const params = {
        type: this.activeName,
        page: "sampleCount",
      };
      getAllList(params).then((res) => {
        if (state) {
          const leftdata = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 1
          );
          const rightdata = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 0
          );
          this.leftdata = leftdata
          res.data.forEach((item) => {
            item.key = item.fieldId;
            item.label = item.fieldNameCn;
          });
          this.checkAlldata = res.data.filter(
            (item) => item.type == this.activeName
          );
          const arr = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 0
          );
          const brr = [];
          arr.forEach((item) => {
            brr.push(item.fieldId);
          });
          this.checkdata = brr;
          this.headlist = this.checkAlldata.filter(
            (item) => item.type == this.activeName && item.isShow == 1
          );
          this.$nextTick(() => {
            this.dataList = []
            this.getList();
            this.$forceUpdate()
          })
        } else {
          this.headlist = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 1
          );

          this.getList();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams.searchValue = undefined;
      this.handleQuery();
    },

    handleSelectable (row) {
      if (row.sjys == this.$store.state.user.nickName) {
        return true;
      } else {
        return false;
      }
    },

    share: function () {
      this.shareReset();
      var form = {};
      var that = this;
      that.form = form;
      var ids = this.ids;
      if (ids == null || ids.length == 0) {
        this.$modal.msgError("请先选择要分享的数据");
        return false;
      } else {
        that.isShareOpen = true;
      }
    },

    getDept () {
      var that = this;
      var dept = this.$store.state.user.dept;
      if (dept != null || dept != undefined) {
        var deptName = dept.deptName;
        var deptId = dept.deptId;
        that.dept.deptName = deptName;
        that.dept.deptId = deptId;
        that.getUser(deptId);
      }
    },

    getUser (deptId) {
      var that = this;
      var form = {};
      form.deptId = deptId;
      that.user.nickName = this.$store.state.user.nickName;
      var userId = this.$store.state.user.userId;
      form.userId = userId;
      that.user.userId = userId;
      getUserListByDeptId(form).then((response) => {
        if (response.code == "200" && response.data) {
          that.userOptions = response.data;
        }
      });
    },

    /** 查询样本统计列表 */
    getList () {
      this.loading = true;
      getSampleListBySampleDecWay(this.queryParams).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleSizeChange (val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange (val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    typeClick (id, sampleDecWay) {
      this.type = id;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.sampleDecWay = sampleDecWay;
      this.activeName = sampleDecWay;
      this.getAllListData();
    },

    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 导出按钮操作 */
    handleExport () {
      var sampleDecWay = this.queryParams.sampleDecWay;
      this.download(
        "check/sample/export",
        {
          ...this.queryParams,
        },
        sampleDecWay + `_sample_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  // height: 100%;
  height: calc(100% - 50px);
  // background: #f2f3f4;
  .concent {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    // background: #ffffff;
    border-radius: 6px 6px 6px 6px;
    opacity: 1;
    box-sizing: border-box;
    padding: 10px 20px;

    .toprow {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      box-sizing: border-box;
      h2 {
        font-weight: bold;
        color: #1f2329;
        font-size: 20px;
        margin: 10px 0 18px 0 !important;
      }
    }
  }
  .rowbtn {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      display: flex;
      .sambtn {
        width: 84px;
        height: 32px;
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
        border: 1px solid #d0d3d6;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 13px;
        cursor: pointer;
        img {
          width: 16px;
          height: 16px;
          margin-right: 10px;
        }
      }
      .button {
        height: 34px;
        background: #efefef;
        color: #595959;
        cursor: pointer;
      }
      .button:hover {
        background: #aa2299;
        color: #ffffff;
      }
      .active {
        background: #aa2299;
        color: #ffffff;
      }
    }
    .right {
      width: 400px;
      height: 34px;
      display: flex;
      .search {
        background: #aa2299;
        color: #ffffff;
        margin-left: 10px;
      }
      .reset {
        background: none;
        color: #1f2329;
      }
    }
  }
  ::v-deep.is-checked {
    .el-checkbox__inner {
      border-color: #aa2290;
      background: #aa2290;
    }
  }
  ::v-deep.el-input.is-focus .el-input__inner {
    border-color: #aa2290 !important;
    box-shadow: 0 0 3px #aa2290 !important;
  }
  ::v-deep.el-card {
    border: none;
  }
  .body {
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-top: 10px;
  }
  .pagefy {
    position: fixed;
    bottom: 20px;
    right: 0;
    color: #1f2329;
  }
  ::v-deep.el-icon-arrow-down {
    font-size: 20px;
  }
  ::v-deep.el-icon-arrow-up {
    font-size: 20px;
  }
  ::v-deep.el-table {
    .el-table__body-wrapper {
      height: calc(100vh - 330px) !important;
    }
  }
}
</style>
